using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace virtuaPol.Util
{
    public class ExtendedList<T> : KeyedCollection<string, T> where T : INamedObject
    {
        public event EventHandler<ListChangedEventArgument<T>> ElementAdded;
        public event EventHandler<ListChangedEventArgument<T>> ElementDeleted;

        public string[] Keys
        {
            get {
                string[] keys = new string[this.Count];
                for (int i = 0; i < this.Count; i++)
                    keys[i] = this[i].Name;
                return keys;
            }
        }

        public ExtendedList()
            : base(null, -1)
        { }
        
        
        public new void Add(T item)
        {
            base.Add(item);
            onElementAdded(new ListChangedEventArgument<T>(item));
        }

        public new bool Remove(T item)
        {
            bool result = base.Remove(item);
            if (result)
                onElementDeleted(new ListChangedEventArgument<T>(item));
            return result;
        }

        protected override string GetKeyForItem(T item)
        {
            return item.Name;
        }

        protected virtual void onElementAdded(ListChangedEventArgument<T> e)
        {
            EventHandler<ListChangedEventArgument<T>> handler = ElementAdded;
            if (handler != null)
                handler(this, e);
        }

        protected virtual void onElementDeleted(ListChangedEventArgument<T> e)
        {
            EventHandler<ListChangedEventArgument<T>> handler = ElementDeleted;
            if (handler != null)
                handler(this, e);
        }

    }

    public class ListChangedEventArgument<T> : EventArgs
    {
        private T element;
        public T Element
        {
            get { return element; }
        }

        public ListChangedEventArgument(T element)
        {
            this.element = element;
        }
    }
}
